package com.example.usermanagement.mybaties;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.usermanagement.context.UserContext;
import com.example.usermanagement.utils.SnowflakeIdWorker;
import com.example.usermanagement.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.ClassUtils;

import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

/**
 * @author yha
 * @ClassName
 * @description:TODO
 * @date 2024年09月10日
 * @version: 1.0.0
 */
@Slf4j
public class MybatisPlusMetaObjectHandler  implements MetaObjectHandler {

    private SnowflakeIdWorker snowflakeIdWorker;

    public MybatisPlusMetaObjectHandler(SnowflakeIdWorker snowflakeIdWorker){
        this.snowflakeIdWorker = snowflakeIdWorker;
    }


    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("mybatis plus start insert fill ....");
        LocalDateTime now = LocalDateTime.now();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(metaObject.getOriginalObject()));
        if(!jsonObject.containsKey("id")|| Objects.isNull(jsonObject.getLong("id"))){
            fillValIfNullByName("id",snowflakeIdWorker.nextId(),metaObject,false);
        }

        if(!jsonObject.containsKey("createTime")||Objects.isNull(jsonObject.get("createTime"))){
            fillValIfNullByName("createTime", now, metaObject, false);
        }

        fillValIfNullByName("createBy", getName(), metaObject, false);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("mybatis plus start update fill ....");
        fillValIfNullByName("updateTime", LocalDateTime.now(), metaObject, true);
        fillValIfNullByName("updateBy", getName(), metaObject, true);
    }

    /**
     * 填充值，先判断是否有手动设置，优先手动设置的值，例如：job必须手动设置
     * @param fieldName 属性名
     * @param fieldVal 属性值
     * @param metaObject MetaObject
     * @param isCover 是否覆盖原有值,避免更新操作手动入参
     */
    private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
        // 1. 没有 get 方法
        if (!metaObject.hasSetter(fieldName)) {
            return;
        }
        // 2. 如果用户有手动设置的值
        Object userSetValue = metaObject.getValue(fieldName);
        String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
        if (StrUtil.isNotBlank(setValueStr) && !isCover) {
            return;
        }
        // 3. field 类型相同时设置
        Class<?> getterType = metaObject.getGetterType(fieldName);
        if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
            metaObject.setValue(fieldName, fieldVal);
        }
    }

    /**
     * 获取 spring security 当前的用户名
     * @return 当前用户名
     */
    private String getName() {
        UserInfoVO userInfoVO = UserContext.getUserInfoVO();
        if (Optional.ofNullable(userInfoVO).isPresent()) {
            return userInfoVO.getName();
        }
        return null;
    }
}
